var express = require('express');
const { path } = require('../app');
var router = express.Router();

//导入lowdb
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync( __dirname+'/../db/db.json');
const db = low(adapter); 

//导入shortid 
const shortid = require('shortid');
const { default: mongoose } = require('mongoose');

//导入moment
const moment = require('moment');


//导入model
const accountmodel = require('../models/accountmodel');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//记账本列表
router.get('/account', function(req, res, next) {

  let accounts = accountmodel.find().sort({time:1}).then((result)=>{

    res.render('accountlist',{accounts:result,moment});
  }).catch((err)=>{
    res.status(500).send('读取数据失败~~');
  });
});

//添加记录
router.get('/account/create', function(req, res, next) {
  res.render('accountcreate');
});

//表单数据提交
router.post('/account', function(req, res, next) {
 
  let data = req.body;

  //直接写法
  /* accountmodel.create({
    title: data.title,
     time: moment(data.time).toDate(),
     type: data.type,
     account: data.account,
     remarks: data.remarks
 }) */
    accountmodel.create({
       ...data,  //ES6语法
       time:moment(data.time).toDate()
    }).then(()=>{
      res.render('success',{msg:"添加成功了哦~~~",url:"/account"});
  
    }).catch((err)=>{
      console.log(err);
    })
});


//删除记录
router.get('/account/:_id', (req, res) => {
  //获取 params 的 id 参数
  let _id = req.params._id;
  //删除
  accountmodel.deleteOne({_id:_id}).then(()=>{
    //提醒
    res.render('success', {msg: '删除成功~~~', url: '/account'});
  }).catch((err)=>{
    console.log(err);
  })
});


 /*  db操作

 // Set some defaults
  db.defaults({ posts: [], user: {} })  可以自定义 里面的对象
  .write()
 //写入数据
// db.get('posts').push({id: 2, title: '今天天气还不错~~'}).write(); 向后添加
// db.get('posts').unshift({id: 3, title: '今天天气还不错~~'}).write();  向前添加
//获取单条数据
// let res = db.get('posts').find({id: 1}).value();
// console.log(res);

//获取数据
// console.log(db.get('posts').value());

//删除数据
// let res = db.get('posts').remove({id: 2}).write();
// console.log(res);

//更新数据
// db.get('posts').find({id: 1}).assign({title: '今天下雨啦!!!'}).write() */
module.exports = router;
